package com.eureka.asyn.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.VoidResult;
import com.eureka.bclass.util.LoggerUtil;

import java.io.InputStream;
import java.text.MessageFormat;
import java.util.List;

/**
 * @Description: 阿里云oss云存储工具类
 * @Author: lixing
 * @Date: 2021/6/14 20:41
 */
public class OssUtil {
    /**
     * @Description 创建bucketName
     * @Author lixing
     * @Date 2021/6/14 21:41
     * @Param [ossClient 实例对象, bucketName 阿里云控制台创建，从配置文件中读取]

     */
    public static void createBucket(OSS ossClient, String bucketName) {
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
        }
    }

    /**
     * @Description 文件存入Bucket
     * @Author lixing
     * @Date 2021/6/14 21:14
     * @Param [
     *  bucketName 阿里云控制台创建，从配置文件中读取
     *  endpoint endpoint是访问OSS的域名。如果您已经在OSS的控制台上创建了Bucket，请在控制台上查看域名
     *  accessKeyId accessKeyId是访问密钥，您可以在控制台上创建和查看
     *  accessKeySecret accessKeySecret是访问密钥，您可以在控制台上创建和查看
     *  inputStream 文件流 fileKey 文件全名(123.png)
     *  fileKey 待上传文件的名称
     * ]
     * @return java.lang.String [上传文件的id]
     */
    public static PutObjectResult putObject(String bucketName, String endpoint, String accessKeyId, String accessKeySecret, InputStream inputStream, String fileKey) {
        // 创建ossClient
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        PutObjectResult putObjectResult = null;
        try {
            // 创建bucketName
            createBucket(ossClient, bucketName);
            // {"clientCRC":-4559966868863618552,"eTag":"F6B306C66AF96F6B6378820D94C4AB08","requestId":"60C7F67A94C77F3435FF6583","serverCRC":-4559966868863618552}
            putObjectResult = ossClient.putObject(bucketName, fileKey, inputStream);
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("阿里云oss云存储工具类删除文件出错：", e.getMessage()));
        } finally {
            // 关闭ossClient
            ossClient.shutdown();
        }
        return putObjectResult;
    }

    /**
     * @Description 删除Bucket中的文件
     * @Author lixing
     * @Date 2021/6/14 21:14
     * @Param [fileKey 待上传文件的名称]

     */
    public static VoidResult deleteObject(String bucketName, String endpoint, String accessKeyId, String accessKeySecret, String fileKey) {
        // 创建ossClient
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            VoidResult voidResult = ossClient.deleteObject(bucketName, fileKey);
            // {"requestId":"60C760F6A7BABC3338A51146","response":{"contentLength":0,"headers":{"Connection":"keep-alive","Content-Length":"0","Date":"Mon, 14 Jun 2021 14:00:22 GMT","Server":"AliyunOSS","x-oss-request-id":"60C760F6A7BABC3338A51146","x-oss-server-time":"14"},"httpResponse":{"allHeaders":[{"buffer":{"empty":false,"full":false},"elements":[{"name":"AliyunOSS","parameterCount":0,"parameters":[]}],"name":"Server","value":"AliyunOSS","valuePos":7},{"buffer":{"empty":false,"full":false},"elements":[{"name":"Mon","parameterCount":0,"parameters":[]},{"name":"14 Jun 2021 14:00:22 GMT","parameterCount":0,"parameters":[]}],"name":"Date","value":"Mon, 14 Jun 2021 14:00:22 GMT","valuePos":5},{"buffer":{"empty":false,"full":false},"elements":[{"name":"0","parameterCount":0,"parameters":[]}],"name":"Content-Length","value":"0","valuePos":15},{"buffer":{"empty":false,"full":false},"elements":[{"name":"keep-alive","parameterCount":0,"parameters":[]}],"name":"Connection","value":"keep-alive","valuePos":11},{"buffer":{"empty":false,"full":false},"elements":[{"name":"60C760F6A7BABC3338A51146","parameterCount":0,"parameters":[]}],"name":"x-oss-request-id","value":"60C760F6A7BABC3338A51146","valuePos":17},{"buffer":{"empty":false,"full":false},"elements":[{"name":"14","parameterCount":0,"parameters":[]}],"name":"x-oss-server-time","value":"14","valuePos":18}],"locale":"zh_CN","params":{"names":[]},"protocolVersion":{"major":1,"minor":1,"protocol":"HTTP"},"statusLine":{"protocolVersion":{"$ref":"$.response.httpResponse.protocolVersion"},"reasonPhrase":"No Content","statusCode":204}},"request":{"contentLength":0,"headers":{"Authorization":"OSS LTAI5tCL1bEMFFSP7vvDhsVi:9BCkon8whKp1+NcBiEMSqK6bP4I=","Date":"Mon, 14 Jun 2021 14:00:23 GMT"},"method":"DELETE","uri":"http://20210614-test.oss-cn-hangzhou.aliyuncs.com/c127f551-d139-4d46-9a2d-28cbbe0ca2c6","useChunkEncoding":false,"useUrlSignature":false},"requestId":"60C760F6A7BABC3338A51146","statusCode":204,"successful":true,"uri":"http://20210614-test.oss-cn-hangzhou.aliyuncs.com/c127f551-d139-4d46-9a2d-28cbbe0ca2c6"}}
            return voidResult;
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("阿里云oss云存储工具类删除文件出错：", e.getMessage()));
            return null;
        } finally {
            // 关闭ossClient
            ossClient.shutdown();
        }
    }

    /**
     * @Description 查看Bucket中的Object
     * @Author lixing
     * @Date 2021/6/14 21:14
     * @return java.lang.String
     */
    public static List<OSSObjectSummary> getObjectSummary(String bucketName, String endpoint, String accessKeyId, String accessKeySecret) {
        // 创建ossClient
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            List<OSSObjectSummary> objectSummary = objectListing.getObjectSummaries();
            return objectSummary;
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("阿里云oss云存储工具类删除文件出错：", e.getMessage()));
            return null;
        } finally {
            // 关闭ossClient
            ossClient.shutdown();
        }
    }

    /**
     * @Description 从url中提取出FileKey
     * @Author lixing
     * @Date 2021/6/18 11:14
     * @Param [url 格式：https://etiger.oss-cn-hangzhou.aliyuncs.com/d2902f61de0f40ad9d7ab35921a0ba3f.mp4]
     * @return java.lang.String [格式：d2902f61de0f40ad9d7ab35921a0ba3f.mp4]
     */
    public static String getFileKeyForUrl(String url) {
        String[] urls = url.split("/");
        String fileKey = urls[urls.length-1];
        return fileKey;
    }

    /**
     * @Description 从url中提取出FileKeyName
     * @Author lixing
     * @Date 2021/6/18 11:14
     * @Param [url 格式：https://etiger.oss-cn-hangzhou.aliyuncs.com/d2902f61de0f40ad9d7ab35921a0ba3f.mp4]
     * @return java.lang.String [格式：d2902f61de0f40ad9d7ab35921a0ba3f]
     */
    public static String getFileKeyNameForUrl(String url) {
        String fileKey = getFileKeyForUrl(url);
        String[] files = fileKey.split(".");
        String fileKeyName = files[0];
        return fileKeyName;
    }

    /**
     * @Description 获取视频的封面
     * @Author lixing
     * @Date 2021/6/21 9:54
     * @Param [videoUrl 视频地址，格式：https://etiger.oss-cn-hangzhou.aliyuncs.com/d2902f61de0f40ad9d7ab35921a0ba3f.mp4]
     * @return java.lang.String
     */
    public static String getVideoCover(String videoUrl, String imgType, int imgWidth, int imgHeight) {
        // https://etiger.oss-cn-hangzhou.aliyuncs.com/d2902f61de0f40ad9d7ab35921a0ba3f.mp4?x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_600,m_fast
        String coverUrl;
        if (imgWidth == 0 && imgHeight == 0) {
            coverUrl = MessageFormat.format("{0}?x-oss-process=video/snapshot,t_1000,f_{1},m_fast", videoUrl, imgType);
        } else {
            coverUrl = MessageFormat.format("{0}?x-oss-process=video/snapshot,t_1000,f_{1},w_{2},h_{3},m_fast", videoUrl, imgType, imgWidth, imgHeight);
        }
        return coverUrl;
    }


}
